package com.jackchong.utils

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.PermissionUtils
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.camera.CustomCameraView
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.style.PictureWindowAnimationStyle
import com.utils.R

/**
 * author : jack(黄冲)
 * e-mail : 907755845@qq.com
 * create : 2020/6/4
 * desc   :
 */
object PhotoUtils {


    @SuppressLint("WrongConstant")
    fun requestedPermissions(activity: Activity, block: () -> Unit){
        val arr = arrayOf(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        PermissionUtils.permission(*arr).callback(object : PermissionUtils.FullCallback {
            override fun onGranted(permissionsGranted: List<String>) {
                block()
            }

            override fun onDenied(permissionsDeniedForever: List<String>, permissionsDenied: List<String>) {
                if (permissionsDeniedForever.isNotEmpty()) {
                    AlertDialog
                        .Builder(activity)
                        .setMessage("权限未开启, 功能将无法正常使用  前往设置-权限管理, 打开权限")
                        .setNegativeButton("取消") { dialogInterface, i -> dialogInterface.cancel() }
                        .setPositiveButton("前往") { dialogInterface, i ->
                            PermissionUtils.launchAppDetailsSettings()
                            dialogInterface.cancel() }
                        .show()
                    ToastUtils.w("权限未开启, 功能将无法正常使用 前往设置-权限管理, 打开权限")
                    return
                }
                ToastUtils.w("权限被拒绝, 功能将无法正常使用")
            }
        }).request()

    }

    fun avatar(activity: Activity, requestCode: Int) {
        openPhoto(activity, 1, requestCode, andCamera = true, clip = true, clipCircle = true)
    }

    /**
     * time    : 2019/4/5 16:55
     * desc    : 打开相册选择照片
     * versions: 1.0
     *
     * @param activity
     * @param maxCount 最多能选择几张
     * @param activity andCamera 是否添加拍照功能
     */
    fun openPhoto(activity: Activity, maxCount: Int, requestCode: Int, andCamera: Boolean = true, clip: Boolean = false, clipCircle: Boolean = false) {
        requestedPermissions(activity){
            PictureSelector.create(activity)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.WeChat)
                .isUseCustomCamera(false)
                .isWeChatStyle(true)
                .imageEngine(GlideEngine.createGlideEngine())
                .setPictureWindowAnimationStyle(PictureWindowAnimationStyle().apply { ofAllAnimation(R.anim.picture_anim_up_in, R.anim.picture_anim_down_out) })
                .isEnableCrop(clip)
                .circleDimmedLayer(clipCircle)
                .showCropFrame(!clipCircle)
                .showCropGrid(!clipCircle)
                .imageSpanCount(4)
                .isPreviewImage(true)// 是否可预览图片
                .isPreviewVideo(true)// 是否可预览视频
                .isCamera(andCamera)
                .minSelectNum(1)
                .maxSelectNum(maxCount)
                .isCompress(true) // 是否压缩
                .selectionMode(PictureConfig.MULTIPLE)
                .synOrAsy(false)
                .glideOverride(160, 160)
                .compressQuality(60)// 图片压缩后输出质量
                .minimumCompressSize(100) // 小于100kb的图片不压缩
                .forResult(requestCode)
        }
    }

    fun openPhoto(fragment: Fragment, maxCount: Int, requestCode: Int, andCamera: Boolean = true, clip: Boolean = false, clipCircle: Boolean = false) {
        requestedPermissions(fragment.requireActivity()){
            PictureSelector.create(fragment)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.WeChat)
                .isUseCustomCamera(false)
                .isWeChatStyle(true)
                .imageEngine(GlideEngine.createGlideEngine())
                .setPictureWindowAnimationStyle(PictureWindowAnimationStyle().apply { ofAllAnimation(R.anim.picture_anim_up_in, R.anim.picture_anim_down_out) })
                .isEnableCrop(clip)
                .circleDimmedLayer(clipCircle)
                .showCropFrame(!clipCircle)
                .showCropGrid(!clipCircle)
                .imageSpanCount(4)
                .isPreviewImage(true)// 是否可预览图片
                .isPreviewVideo(true)// 是否可预览视频
                .isCamera(andCamera)
                .minSelectNum(1)
                .maxSelectNum(maxCount)
                .isCompress(true) // 是否压缩
                .selectionMode(PictureConfig.MULTIPLE)
                .synOrAsy(false)
                .glideOverride(160, 160)
                .compressQuality(60)// 图片压缩后输出质量
                .minimumCompressSize(100) // 小于100kb的图片不压缩
                .forResult(requestCode)
        }
    }

    fun obtainSimpleResult(data: Intent): MutableList<String>{
        val selectList = PictureSelector.obtainMultipleResult(data)
        val list = ArrayList<String>()
        selectList.forEach {
            val path: String
            if (it.isCut && !it.isCompressed) {
                // 裁剪过
                path = it.cutPath
            } else if (it.isCompressed || it.isCut && it.isCompressed) {
                // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                path = it.compressPath
            } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q && !it.androidQToPath.isNullOrEmpty()) {
                // Android Q
                path = it.androidQToPath
            } else if (it.isOriginal){
                // 原始路径
                path = it.originalPath
            } else {
                //原图路径
                path = it.path
            }
            list.add(path)
        }
        return list
    }


    fun openCamera(activity: Activity, requestCode: Int, clip: Boolean = false, clipCircle: Boolean = false){
        PictureSelector.create(activity)
            .openCamera(PictureMimeType.ofImage())
            .theme(R.style.WeChat)
            .isUseCustomCamera(false)
            .imageEngine(GlideEngine.createGlideEngine())
            .isEnableCrop(clip)
            .isCompress(true) // 是否压缩
            .selectionMode(PictureConfig.SINGLE)
            .synOrAsy(false)
            .glideOverride(160, 160)
            .compressQuality(60)// 图片压缩后输出质量
            .circleDimmedLayer(clipCircle)
            .showCropFrame(!clipCircle)
            .showCropGrid(!clipCircle)
            .setButtonFeatures(CustomCameraView.BUTTON_STATE_ONLY_CAPTURE) //拍照, 录制, 拍照或录制
            .minimumCompressSize(100) // 小于100kb的图片不压缩
            .forResult(requestCode)
    }

    fun openCamera(fragment: Fragment, requestCode: Int, clip: Boolean = false, clipCircle: Boolean = false){
        PictureSelector.create(fragment)
            .openCamera(PictureMimeType.ofImage())
            .theme(R.style.WeChat)
            .isUseCustomCamera(false)
            .imageEngine(GlideEngine.createGlideEngine())
            .isEnableCrop(clip)
            .isCompress(true) // 是否压缩
            .selectionMode(PictureConfig.SINGLE)
            .synOrAsy(false)
            .glideOverride(160, 160)
            .compressQuality(60)// 图片压缩后输出质量
            .circleDimmedLayer(clipCircle)
            .showCropFrame(!clipCircle)
            .showCropGrid(!clipCircle)
            .setButtonFeatures(CustomCameraView.BUTTON_STATE_ONLY_CAPTURE) //拍照, 录制, 拍照或录制
            .minimumCompressSize(100) // 小于100kb的图片不压缩
            .forResult(requestCode)
    }


    interface OnResultsListener<T>{
        fun onResults(t: T)
    }
}